package com.etc.controller;

import com.etc.entity.Room;
import com.etc.entity.Type;
import com.etc.entity.User;
import com.etc.service.UserService;
import com.etc.util.PasswordUtil;
import com.github.pagehelper.PageInfo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2021-10-18 21:07:18
 */
@Controller
@RequestMapping("user")
public class UserController {
    Logger logger = Logger.getLogger(UserController.class);
    /**
     * 服务对象
     */
    @Autowired
    private UserService userService;

    /**
     * 用户注册
     * @param userName
     * @param password

     */
    @RequestMapping(value = "/regist",produces = "text/html;charset=utf-8")
    public void  regist(@RequestParam("userName") String userName,
                        @RequestParam("password") String password, HttpServletResponse response, HttpSession session ) throws IOException {

        //密码加密加盐
        String salt= PasswordUtil.salt();
        String md5Password= PasswordUtil.md5(password+salt);
        User user = new User(userName, md5Password,salt);
        user.setUserLevel(2);

        boolean flag = userService.regist(user);
        session.setAttribute("flag",flag);
        if(flag) {
            response.getWriter().print("<script>location.href='../front/login.jsp'</script>");
        }
    }
    //用户登录
    @RequestMapping(value = "/login")
    public void login(@RequestParam(value = "userName",defaultValue = "") String userName,
                      @RequestParam(value = "password",defaultValue = "") String password,
                      HttpSession session , HttpServletResponse response) throws IOException {

        //根据用户名获取salt
        String salt = userService.getUsersaltByUserName(userName);

        //获取密码
        String md5Password = PasswordUtil.md5(password + salt);

        PrintWriter out = response.getWriter();
        //调用业务层
        User user = userService.login(userName, md5Password);
        logger.debug(user);
        if (user!=null){
            if (user.getUserState()==0 && user.getUserLevel()==0){
                session.setAttribute("frontUser",user);
                response.getWriter().print("<script>location.href='../front/showUser.jsp'</script>");

            }else if (user.getUserState()==0 && (user.getUserLevel()==2|| user.getUserLevel()==1)){
                session.setAttribute("frontUser",user);
                response.getWriter().print("<script>location.href='../front/dousha.jsp'</script>");

            }
        }else{
            response.sendRedirect("../front/login.jsp");

        }


    }

    /**
     * 修改用户等级为主播
     * @return
     */
    @RequestMapping("setLevelTwo")
    @ResponseBody
    public boolean setLevelTwo(@RequestParam(value = "userId") String userId){
        return userService.setLevelTwo(userId);
    }
    
    //退出登录
    @RequestMapping("/exit")
    @ResponseBody
    public void exit(HttpServletRequest request){
        request.getSession().removeAttribute("frontUser");

    }

    @RequestMapping("/checkName")
    @ResponseBody
    //查询所有用户
    public void checkName(@RequestParam(value = "userName") String userName, HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        //获取所有用户
        List<User> list = userService.getQueryAllUsers();
        int flag=0;
        //遍历所有用户
        for (User user : list) {
            //如果用户名已存在 直接返回
            if(user.getUserName().equals(userName)) {
                out.print("该用户名已存在,请换一个吧~");
                return;
            }else {
                flag=1;
            }
        }
        if(flag==1) {
            out.write("可用");
        }
    }
    @RequestMapping("/checkNameById")
    @ResponseBody
    //查询单个用户
    public User checkNameById(@RequestParam(value = "userId") String userId ) {


        User user = userService.queryById(userId);
        return user;


    }
    @RequestMapping("/Pay")
    public  void Pay(@RequestParam("userId")String userId,@RequestParam("price") String price, HttpServletResponse response) throws IOException {
        boolean b = userService.upUserPriceById(userId,price);
        response.getWriter().print("<script>location.href='../front/dousha.jsp'</script>");

    }
    @RequestMapping("/home1")
    public ModelAndView home( )  {


        ModelAndView view = new ModelAndView();
        view.setViewName("forward:/front/dousha.jsp");

//        response.getWriter().print("<script>location.href='../front/dousha.jsp'</script>");
        return view;

    }


    /*@RequestMapping("/ailpay")
    public void ailpay(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.gatewayUrl, AliPayConfig.app_id, AliPayConfig.merchant_private_key, "json", AliPayConfig.charset, AliPayConfig.alipay_public_key, AliPayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AliPayConfig.return_url);
        alipayRequest.setNotifyUrl(AliPayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
        String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
        //订单名称，必填
        String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");


        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","

                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //输出
        response.getWriter().println(result);


    }*/
    /**
     * 查询所以视频
     * @return
     */
    @RequestMapping("getQueryAllUser")
    @ResponseBody
    public PageInfo<User> getQueryAllUser(@RequestParam(value = "pageNum") int pageNum,
                                          @RequestParam(value = "pageSize") int pageSize
                                       ){
        PageInfo<User> pageInfo = userService.queryAllUser(pageNum,pageSize);

        return pageInfo;
    }
    //删除用户
    @RequestMapping("deleteUser")
    @ResponseBody
    //查询单个用户
    public boolean deleteUser(@RequestParam(value = "userId") String userId ) {
        return userService.deleteUserById(userId);
    }
    //用户添加
    @RequestMapping(value = "/adduser",produces = "text/html;charset=utf-8")
    public void  adduser(@RequestParam("userName") String userName,
                         @RequestParam("password") String password,
                         @RequestParam("userPhone") String userPhone,

                         @RequestParam("userLevel") Integer userLevel,
                         @RequestParam("userImg") MultipartFile userImg,
                         @RequestParam("userPrice") BigDecimal userPrice, HttpServletResponse response) throws IOException {
        String userImgName= UUID.randomUUID()+userImg.getOriginalFilename();
        File imgfile = new File("D:\\userImg\\" + userImgName);

        try {
            userImg.transferTo(imgfile);

        } catch (IOException e) {
            e.printStackTrace();
        }

        //密码加密加盐
        String salt= PasswordUtil.salt();
        String md5Password= PasswordUtil.md5(password+salt);
        User user = new User(userName, md5Password,salt,userPhone,0,userLevel,userImgName,userPrice);

        boolean flag = userService.regist(user);

        if(flag) {
            response.getWriter().print("<script>location.href='../front/showUser.jsp'</script>");
        }
    }
    @RequestMapping("frontUserImg")
    public void frontUserImg(@RequestParam(value = "userImg") String userImg, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        //返回的数据类型
        response.setContentType("application/pdf");
        //响应头
        response.setHeader("Content-Disposition", "attachment;fileName=" + userImg);
        InputStream inputStream=null;
        OutputStream outputStream=null;
        //路径
        String path ="E:\\userImg"+ File.separator+File.separator;
        
        byte[] bytes = new byte[2048];
        try {
            File filePath = new File(path,userImg);
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();// 如果目录不存在，则创建目录
            }
            inputStream = new FileInputStream(filePath);
            outputStream = response.getOutputStream();
            int length;
            //inputStream.read(bytes)从file中读取数据,-1是读取完的标志
            while ((length = inputStream.read(bytes)) > 0) {
                //写数据
                outputStream.write(bytes, 0, length);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭输入输出流
            if(outputStream!=null) {
                outputStream.close();
            }
            if(inputStream!=null) {
                inputStream.close();
            }
        }
    }

    //修改用户
    @RequestMapping(value = "/updateUser",produces = "text/html;charset=utf-8")
    public void  updateUser(@RequestParam("userId") String userId, @RequestParam("userName") String userName,
                            @RequestParam("password") String password,
                            @RequestParam("userPhone") String userPhone,
                            @RequestParam("userState") Integer userState,
                            @RequestParam("userLevel") Integer userLevel,
                            @RequestParam("userImg") MultipartFile userImg,
                            @RequestParam("userPrice") String userPrice, HttpServletResponse response ) throws IOException {
        String userImgName= UUID.randomUUID()+userImg.getOriginalFilename();
        File imgfile = new File("D:\\userImg\\" + userImgName);

        try {
            userImg.transferTo(imgfile);

        } catch (IOException e) {
            e.printStackTrace();
        }
        //密码加密加盐
        String salt= PasswordUtil.salt();
        String md5Password="";
        if(password!=null&& "".equals(password)){
              md5Password= PasswordUtil.md5(password+salt);

          }
        BigDecimal i = new BigDecimal(userPrice);


        User user = new User(userId,userName, md5Password,salt,userPhone,userState,userLevel,userImgName,i);
        logger.debug(user);
        boolean flag = userService.upUserById(user);

        if(flag) {
            response.getWriter().print("<script>location.href='../front/showUser.jsp'</script>");
        }
    }

}

